package sjtu.ist.warehouse4ws.dao;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sjtu.ist.warehouse4ws.model.ShiroUser;

public class ShiroUserDaoHibernate extends BaseDaoHibernate<ShiroUser>
		implements ShiroUserDao {

	public ShiroUser findUser(String username) {
		SQLQuery query = getSession().createSQLQuery(
				"select * from shiro_user where shiro_user.username='"
						+ username + "'");
		List<ShiroUser> users = query.addEntity(ShiroUser.class).list();
		return users.size() > 0 ? users.get(0) : null;

	}

	public List<ShiroUser> findCompanyUser(int companyId) {

		SQLQuery query = getSession().createSQLQuery(
				"select * from shiro_user where shiro_user.companyId='"
						+ companyId + "'");
		List<ShiroUser> users = query.addEntity(ShiroUser.class).list();
		return users.size() > 0 ? users : null;

	}

	public ShiroUser getUser(long userId) {
		SQLQuery query = getSession().createSQLQuery(
				"select * from shiro_user where shiro_user.userId='" + userId
						+ "'");
		List<ShiroUser> users = query.addEntity(ShiroUser.class).list();
		return users.size() > 0 ? users.get(0) : null;
	}

	public void saveShiroUser(ShiroUser user) {
		getHibernateTemplate().setFlushMode(HibernateTemplate.FLUSH_EAGER);
		getHibernateTemplate().save(user);

	}

	@Override
	public void updateShiroUser(ShiroUser user) {
		// TODO Auto-generated method stub
		getHibernateTemplate().setFlushMode(HibernateTemplate.FLUSH_EAGER);
		getHibernateTemplate().update("ShiroUser", user);
	}

	@Override
	public List<ShiroUser> getUserList(Integer companyId, String role) {
		// TODO Auto-generated method stub
		return getHibernateTemplate().find(
				"from ShiroUser u where u.companyId='" + companyId
						+ "' and 'user' in u.shiroRoles");
	}

	@Override
	public void delete(Integer id) {
		// TODO Auto-generated method stub
		getHibernateTemplate().setFlushMode(HibernateTemplate.FLUSH_EAGER);
		getHibernateTemplate().delete(
				getHibernateTemplate().get(ShiroUser.class, id));
	}
}
